﻿class Snake {
    private _way: DIRECTION;
    private _head: Point;
    private _list: Array<Section>;

    constructor(count: number) {
        this._list = [];
        this._way = DIRECTION.RIGHT;

        let p = new Point(150, 150);
        for (let i = 0; i < count; i++) {
            let sec = new Section();
            sec.num = i;
            sec.position = p;

            this._list.push(sec);

            if (i == 0) {
                this._head = new Point(p.x, p.y);
            }

            p.x += 10;
        }
    }

    move() {
        let head = this._head;

        switch (this._way) {
            case DIRECTION.LEFT:
                head.x -= 10;
                break;
            case DIRECTION.RIGHT:
                head.x += 10;
                break;
            case DIRECTION.TOP:
                head.y -= 10;
                break;
            case DIRECTION.BOTTOM:
                head.y += 10;
                break;
        }
        let sec = new Section();
        sec.position = head;

        this._list.unshift(sec);
        this._head = head;

        this._list.pop();
    }

    isOver(): boolean {
        let head = this._head;

        // catch wall
        if (head.x < 50 || head.y < 50 || (head.x + 10) > 450 || (head.y + 10) > 450) {
            console.log("catch all");
            return true;
        }

        //catch itself
        for (let i = 1; i < this._list.length; i++) {
            let sec = this._list[i];
            if (head.x == sec.position.x &&
                head.y == sec.position.y) {
                return true;
            }
        }

        return false;
    }

    get Head(): Point {
        return this._head
    }

    set Head(h: Point) {
        this._head = h;
    }

    draw(ctx: CanvasRenderingContext2D): void {
        let oldStyle = ctx.fillStyle;

        ctx.fillStyle = "#7F7F7F"

        for (let sec of this._list) {
            sec.draw(ctx);
        }

        ctx.fillStyle = oldStyle;
    }

    get way(): DIRECTION {
        return this._way;
    }

    set way(d: DIRECTION) {
        this._way = d;
    }

    eatFood(): void {
        let head = this._head;

        //move head
        switch (this._way) {
            case DIRECTION.LEFT:
                head.x -= 10;
                break;
            case DIRECTION.RIGHT:
                head.x += 10;
                break;
            case DIRECTION.TOP:
                head.y -= 10;
                break;
            case DIRECTION.BOTTOM:
                head.y += 10;
                break;
        }

        let sec = new Section();
        sec.position = head;

        this._list.unshift(sec);
        this._head = head;
    }
}